define(["moment", "module/moduleA/program/B01/custom_layout/default-config.js"], function (moment) {
    return ["$scope", "$filter", "$stateParams", "config", "MMWService", "$calculater", "$mdDialog", "$state", '$mddProvider',
    function ($scope, $filter, $stateParams, config, $MMWService, $calculater, $mdDialog, $state, $mddProvider) {
        $scope._event = {};
        dialog = {};
        $scope._fn = {};
        $scope.init = function () {
            //$MMWService.PNIGList = {};
            $scope.wo_no = '';
            $scope.process_op_detail = [];
            $scope.type = $stateParams.data;
            $scope.mode = 'init';
            $scope.printList = []; // 列印詳情

            $scope.packList = [];
            $scope.moreInfoList = [];
            $scope.showFlag = false;
            $scope.showTipsFlag = false;
            $scope.moList = [];
            $scope.headerList = [];

            $scope.list = [
                'wo_no_display', 'process_display', 'so_display', 'item_display', 'customer_no', 'item_name', 'customer_name', 'item_spec',
                'BoxQty', 'CartonQty', 'ERPMoLineNo', 'FACTORYNO', 'LOTSTDQty', 'MPQty', 'MoDescription', 'MoSource', 'MoUser_Defined01', 'MoUser_Defined02', 'MoUser_Defined03', 'MoUser_Defined04', 'MoUser_Defined05','MoUser_Defined06','MoUser_Defined07','MoUser_Defined08',' MoUser_Defined09','MoUser_Defined10', 'MoUser_Defined11', 'MoUser_Defined12', 'MoUser_Defined13','MoUser_Defined14','MoUser_Defined15','MoUser_Defined16','MoUser_Defined17','MoUser_Defined18','MoUser_Defined19','MoUser_Defined20','MoUser_Defined21', 'MoUser_Defined22', 'MoUser_Defined23','MoUser_Defined24','MoUser_Defined25','MoUser_Defined26','MoUser_Defined27','MoUser_Defined28','MoUser_Defined29','MoUser_Defined30','MoUser_Defined31','MoUser_Defined32','MoUser_Defined33','MoUser_Defined34', 'PLANFINISHDATE',
                'PRODUCTTYPE', 'PalletQty', 'PrdDescription', 'palletqty', 'PrdUser_Defined01', 'PrdUser_Defined02', 'PrdUser_Defined03', 'PrdUser_Defined04', 'PrdUser_Defined05','PrdUser_Defined06','PrdUser_Defined07','PrdUser_Defined08','PrdUser_Defined09','PrdUser_Defined10', 'PrdUser_Defined11', 'PrdUser_Defined12', 'PrdUser_Defined13', 'PrdUser_Defined14','PrdUser_Defined15','PrdUser_Defined16','PrdUser_Defined17','PrdUser_Defined18','PrdUser_Defined19','PrdUser_Defined20','PrdUser_Defined21', 'PrdUser_Defined22', 'PrdUser_Defined23','PrdUser_Defined24','PrdUser_Defined25','PrdUser_Defined26','PrdUser_Defined27','PrdUser_Defined28','PrdUser_Defined29','PrdUser_Defined30','PrdUser_Defined31','PrdUser_Defined32','PrdUser_Defined33','PrdUser_Defined34','ProductCode', 'ProductPCSNo',
                'QCCategory', 'SerialTypeNo_COMP', 'SerialTypeNo_LOT', 'SpecNo', 'StockInLotNo', 'Storage_Spaces_No', 'Warehouse_No', 'default_date', 'disposed_unit', 'graph_no', 'is_urgent', 'item_no', 'item_ver', 'max_expand_qty', 'plan_start_date', 'priority', 'process_no', 'process_ver', 'so_no', 'so_seq', 'std_qty', 'untreated_qty', 'wo_no', 'wo_qty', 'wo_type_name', 'wo_type_no'
            ];
            $scope.searchList = [
                'page_no', 'productno', 'productname', 'moqty', 'boxqty', 'cartonqty', 'create_date', 'customerno', 'erpmolineno', 'factoryno', 'graphno', 'itemno', 'itemspec', 'lotstdqty', 'modescription', 'mosource', 'mounitno', 'mouser_defined01', 'mouser_defined02', 'mouser_defined03', 'mouser_defined04', 'mouser_defined05','mouser_defined06','mouser_defined07','mouser_defined08','mouser_defined09','mouser_defined10', 'mouser_defined11', 'mouser_defined12',
                'mouser_defined13', 'mouser_defined14', 'mouser_defined15', 'mouser_defined16', 'mouser_defined17', 'mouser_defined18', 'mouser_defined19', 'mouser_defined20', 'mouser_defined21', 'mouser_defined22', 'mouser_defined23','mouser_defined24','mouser_defined25','mouser_defined26','mouser_defined27','mouser_defined28','mouser_defined29','mouser_defined30','mouser_defined31','mouser_defined32','mouser_defined33','mouser_defined34', 'mpqty', 'palletqty', 'plan_start_date', 'planfinishdate', 'prddescription', 'prduser_defined01', 'prduser_defined02', 'prduser_defined03', 'prduser_defined04', 'prduser_defined05','prduser_defined06','prduser_defined07','prduser_defined08','prduser_defined09','prduser_defined10', 'prduser_defined11', 'prduser_defined12', 'prduser_defined13',
                'prduser_defined14','prduser_defined15','prduser_defined16','prduser_defined17','prduser_defined18','prduser_defined19','prduser_defined20', 'prduser_defined21','prduser_defined22','prduser_defined23','prduser_defined24',
                'prduser_defined25', 'prduser_defined26','prduser_defined27','prduser_defined28','prduser_defined29','prduser_defined30','prduser_defined31','prduser_defined32','prduser_defined33','prduser_defined34', 'priority', 'productcode', 'productpcsno', 'producttype', 'productversion', 'qccategory', 'rono', 'serialtypeno_comp', 'serialtypeno_lot', 'specno', 'stockinlotno', 'storage_spaces_no', 'unreleaselotqty', 'warehouse_no','customername','motypename'

            ];
            $scope.layout();
        };

        $scope.layout = function () {
            if (localStorage.getItem('customLayout')) {
                var settingsList = JSON.parse(localStorage.getItem('customLayout'));
                // 生产批开立工单部分
                var settingsIdx = settingsList.findIndex(function (item) {
                    return item.page_id == 'WIP001' && item.div_id == 'mo';
                });
                if (settingsIdx !== -1 && settingsList[settingsIdx].view_desc) {
                    $scope.packList = JSON.parse(settingsList[settingsIdx].view_desc).data;
                    $scope.moreInfoList = JSON.parse(settingsList[settingsIdx].view_desc).list;
                }
                if ($scope.packList.length == 0) {
                    $scope.showFlag = false;
                } else {
                    $scope.showFlag = true;
                }
                // 生产批开立工单号开窗
                $scope.moList = [];
                $scope.headerList = [];
                var moSettingsIdx = settingsList.findIndex(function (item) {
                    return item.page_id == 'WIP001' && item.div_id == 'moselect';
                });
                if (moSettingsIdx !== -1 && settingsList[moSettingsIdx].view_desc) {
                    let tempList = JSON.parse(settingsList[moSettingsIdx].view_desc).data;
                    tempList.forEach(t => {
                        $scope.moList.push(t.col[0]);
                    });
                }
                if ($scope.moList.length == 0) {
                    $scope.headerList = [
                        { label: $filter('translate')('common.queryList.wo_c'), code: 'page_no' },
                        { label: $filter('translate')('common.queryList.item_c'), code: 'productno' },
                        { label: $filter('translate')('common.queryList.item_n'), code: 'productname' },
                        { label: $filter('translate')('B0101.queryList.prdtype'), code: 'producttype' },
                        { label: $filter('translate')('B0101.queryList.prdsepc'), code: 'itemspec' },
                        { label: $filter('translate')('common.queryList.wo_no_qty'), code: 'moqty', width: '110px' },
                        { label: $filter('translate')('B0101.queryList.plan_start_date'), code: 'plan_start_date' },
                        { label: $filter('translate')('B0101.queryList.PLANFINISHDATE'), code: 'planfinishdate' },
                    ];
                } else {
                    $scope.moList.forEach(m => {
                        $scope.headerList.push({
                            label: m.fieldName,
                            code: m.fieldId
                        });
                    });
                }
            } else {
                $scope.headerList = [
                    { label: $filter('translate')('common.queryList.wo_c'), code: 'page_no' },
                    { label: $filter('translate')('common.queryList.item_c'), code: 'productno' },
                    { label: $filter('translate')('common.queryList.item_n'), code: 'productname' },
                    { label: $filter('translate')('B0101.queryList.prdtype'), code: 'producttype' },
                    { label: $filter('translate')('B0101.queryList.prdsepc'), code: 'itemspec' },
                    { label: $filter('translate')('common.queryList.wo_no_qty'), code: 'moqty', width: '110px' },
                    { label: $filter('translate')('B0101.queryList.plan_start_date'), code: 'plan_start_date' },
                    { label: $filter('translate')('B0101.queryList.PLANFINISHDATE'), code: 'planfinishdate' },
                ];
            }
        };

        $scope.back = function(){
            $scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);
        };

        $scope.barcodeScan = function(event){
            if(event.keyCode == 13){
                $scope.search();
            }
        };

        $scope.getStyle = function (option) {
            return {
                //flex: option.width + ' ' + option.width + ' ' + option.width*300 + 'px',
                width:option.width*300 + 'px',
                fontSize: option['font-size'] + 'px',
                color: option.color,
                fontWeight: option.bold
            }
        }

        $scope.getStyle2 = function (option) {
            if(option.bold !== 'bold') {
                option.bold = 400
            }
            return {
                fontSize: option['font-size'] + 'px',
                color: option.color,
                fontWeight: option.bold
            }
        }

        $scope.getStyle3 = function (option) {
            return {
                width: option.length * 300 + 'px'
            }
        }

        $scope.showTips = function () {
            var height = $("#table_id").height();
            var popovertip = $("#more_id");
            popovertip.css('top', height + 70 + 'px');
            $scope.showTipsFlag = true;
        }

        $scope.hideTips = function () {
            $scope.showTipsFlag = false;
        }

        $scope.loadSysSettings = function () {
            var resultList = [];
            resultList.push({ code: 'mo', label: $filter('translate')('customLayout.moName') });
            resultList.push({ code: 'moselect', label: $filter('translate')('customLayout.moselectName') });
            $scope.showSelect({
                title: $filter('translate')('common.msg.plz_select'),
                label: 'label',
                code: 'code',
                list: resultList,
                confirm: function (item, d) {
                    d.hide();
                    let tempList = {};
                    var divId = '';
                    var styleFlag = true; // 是否控制行数限制
                    var moreFlag = false; // 是否显示更多排版页签
                    if (item.code == 'mo') {
                        divId = 'mo';
                        moreFlag = true;
                        $scope.list.forEach(l => {
                            tempList[l] = null;
                        });
                    } else {
                        divId = 'moselect';
                        styleFlag = false;
                        $scope.searchList.forEach(l => {
                            tempList[l] = null;
                        });
                    }

                    $mdDialog.serviceDialog('customerLayoutService', {
                        pageId: 'WIP001',
                        divId: divId,
                        styleFlag: styleFlag,
                        moreFlag: moreFlag,
                        list: tempList,
                        callback: function () {
                            $scope.layout();
                        }
                    });

                }
            });
        };

        $scope.search = function(){
            if($scope.wo_no != ''){
                var content = {
                    type : $scope.type,
                    wo_no : $scope.wo_no
                };
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_WIP.wo_info_get',
                    content : content,
                    success : function(data){
                        $scope.workItem = data;
                        // 如果後台沒有傳回預計開工日，那就呈現今天的日期。
                        if(data.default_date != ''){
                            $scope.workItem.default_date = data.default_date;
                        } else {
                            $scope.workItem.default_date = moment().format('YYYY/MM/DD');
                        };
                        $scope.workItem.wo_no_display = $scope.workItem.wo_no + '(' +  $scope.workItem.wo_type_name + ')';
                        $scope.workItem.expand_qty = $scope.workItem.untreated_qty;
                        $scope.workItem.treated_qty = $calculater.decimalSub((+$scope.workItem.wo_qty), (+$scope.workItem.untreated_qty));
                        $scope.workItem.so_display = $scope.workItem.so_no + '(' + $scope.workItem.so_seq + ')';
                        $scope.workItem.item_display = $scope.workItem.item_no + ' (' + $scope.workItem.item_ver + ')';
                        $scope.process_op_detail = [];
                        $scope.std_qty_isChanged = false;
                        $scope.untreated_qty_over = 0;
                        $scope.plotItem = [];
                        if($scope.type == '1'){
                            $scope.workItem.expand_qty = '';
                        }
                        //20170516 modify by Dustdusk for 如果沒有標準批量，則應預設為下線數量
                        if(!$scope.workItem.std_qty || $scope.workItem.std_qty == 0){
                            $scope.workItem.std_qty = $scope.workItem.expand_qty;
                        }

                        //設定預設值
                        //M# 75128 改取工單開立綁定的流程 如果為空才取 預設流程
                        var check_process_no = typeof $scope.workItem.process_no  == "undefined" || $scope.workItem.process_no == "";
                        var check_process_ver = typeof $scope.workItem.process_ver  == "undefined" || $scope.workItem.process_ver == "";
                        if(check_process_no && check_process_ver)
                        {
                            //取預設流程
                            $scope.workItem.process_detail.forEach(function(detail){
                                if(detail.is_default == '1'){
                                    $scope.workItem.process_display = detail.process_no+'('+detail.process_ver+')';
                                    $scope.workItem.process_no = detail.process_no;
                                    $scope.workItem.process_ver = detail.process_ver;
                                    $scope.process_op_detail = detail.op_station;
                                    $scope.process_op_detail.forEach(function(item){
                                        item.index = 0;
                                    });
                                }
                            });
                        }
                        else
                        {   //20220413 modi by wangyq for M#110359 filter("filter")是模糊匹配,如果编号前几位一样就会匹配出来导致显示错误
                            //取綁定流程
                            //var p_condition = {
                                //process_no:$scope.workItem.process_no,
                                //process_ver:$scope.workItem.process_ver
                            //};
                            //var current_process = $filter("filter")($scope.workItem.process_detail,p_condition);
							var isOK = false;
							$scope.workItem.process_detail.forEach(function(detail){
                                if(detail.process_no == $scope.workItem.process_no & detail.process_ver == $scope.workItem.process_ver ){
								    isOK = true;
                                    $scope.workItem.process_display = detail.process_no+'('+detail.process_ver+')';
                                    $scope.workItem.process_no = detail.process_no;
                                    $scope.workItem.process_ver = detail.process_ver;
                                    $scope.process_op_detail = detail.op_station;                                   
                                }
                               });
                            // 20210419 modifyBy 14581 for M#90941 : 比對失敗時，預帶第一筆流程選項
                            //var default_process = angular.copy($scope.workItem.process_detail[0])
                            //if(current_process.length > 0) {
                                //$scope.workItem.process_display = current_process[0].process_no+'('+current_process[0].process_ver+')';
                                //$scope.workItem.process_no = current_process[0].process_no;
                               // $scope.workItem.process_ver = current_process[0].process_ver;
                               // $scope.process_op_detail = current_process[0].op_station;
                            if(isOK == false) {//} else {
				              //取預設流程 20220413 modi by wangyq for M#110359 工单取不到依然要默认产品默认流程
                               $scope.workItem.process_detail.forEach(function(detail){
                                if(detail.is_default == '1'){
                                    $scope.workItem.process_display = detail.process_no+'('+detail.process_ver+')';
                                    $scope.workItem.process_no = detail.process_no;
                                    $scope.workItem.process_ver = detail.process_ver;
                                    $scope.process_op_detail = detail.op_station;                                  
                                }
                               });
                                //$scope.workItem.process_display = `${default_process.process_no}(${default_process.process_ver})`;
                                //$scope.workItem.process_no = default_process.process_no;
                                //$scope.workItem.process_ver = default_process.process_ver;
                                //$scope.process_op_detail = default_process.op_station;
                            }
                            $scope.process_op_detail.forEach(function(item){
                                item.index = 0;
                            });
                        }
                    }
                });
            } else {
                $scope.$root.showAlert($filter('translate')('B0101.msg.column1'));
            }
        };
        //查询按钮
        $scope._fn['B0101_search'] = {
        isShown: 'N',
            click: () => {
                $scope.search();
            }
        };

          // 生产批开立，不能为0做卡控20230101 add by shiwl for M# 0149162: 【敏达零部件】6.0测试区生产批开立数量为0也能开立成功，但是生产批现况表里没有数据，需要加卡控
          $scope._event['plotItem.plot_qty'] = {
            click: (event) => {
                $scope.input_plot_qty(event);
            }
         };

        //工单号查询
        $scope._event['B0101_wo_no'] = {
            click: () => {
                $scope.loadWoNoList();
            }
        };

        //流程查询
        $scope._event['B0101_WoInfoprocess_display'] = {
            click: () => {
                $scope.loadProcesstDetail();
            }
        };

        //优先权数字设置
        $scope._event['B0101_PlotInfopriority'] = {
            click: (event) => {
                $scope.input_priority(event);
            }
        };

        //下线数量数字设置
        $scope._event['B0101_PlotInfoexpand_qty'] = {
            click: (event) => {
                $scope.input_expand_qty(event);
            }
        };

        //标准批量数字设置
        $scope._event['B0101_PlotInfostd_qty'] = {
            click: (event) => {
                $scope.input_std_qty(event);
            }
        };

        //计算批数设置
        $scope._fn['B0101_PlotInfoexpand'] = {
            click: () => {
                $scope.sendExpand();
            }
        };

        //生产批开立方法
        $scope._fn['B0101_btn_confirm'] = {
            click: () => {
                $scope.confirm();
            }
        };

        $scope._event['pdf_panel'] = {
            isShown:'N'
        }
        $scope._event['pdf_footer'] = {
            isShown:'N'
        }

        $scope.$watch('mode', (mode) => {
            if(mode == 'init') {
                $scope._event['pdf_panel'].isShown = 'N'
                $scope._event['pdf_footer'].isShown = 'N'
            }
            else if (mode == 'print'){
                $scope._event['pdf_panel'].isShown = 'Y'
                $scope._event['pdf_footer'].isShown = 'Y'
            } 
        });

        //工單查詢選完直接帶出資料
        $scope.loadWoNoList = function(){
            if($scope.type == '1' && $scope.wo_no.length<5){
                //當生產批補開立的時候，工單號要至少五個字
                $scope.$root.showAlert($filter('translate')('B0101.errorMsg.wo_no_length'));
                return;
            }

            $MMWService.showQueryListPNIG({
                setting: true, // 20201228 FOR 83491 自定义排版
                //page_mode: 1,
                form_name: 'PageNo_3',
                pageRecord:50,
                condition: [
                    {name:$filter('translate')('common.queryList.wo_c'), column_name:'MONo', query_mode:'2', value:$scope.wo_no}
                ],
                header: $scope.headerList,
                setCondition:function(conditions){
                    conditions.push({column_name:'MOSTATE', query_mode:'0', value:'3', merge_condition_model:'AND' });
                    if($scope.type == '0'){
                        conditions.push({column_name:'UnReleaseLotQty', query_mode:'6', value:'0', merge_condition_model:'AND' });
                    } else if($scope.type == '1'){
                        conditions.push({column_name:'UnReleaseLotQty', query_mode:'5', value:'0', merge_condition_model:'AND' });
                    }
                    return conditions;
                },
                selectCode:$scope.wo_no,
                confirm : function(selectItem){
                    $scope.wo_no = selectItem.page_no;
                    $scope.search();
                }
            });
        };

        //20220808 add by 王晴晴 for M#0103512:生产批开立中点击流程开窗，新增[签核状态]和[说明]的栏位
        $scope.loadProcesstDetail = function(){
            if($scope.workItem){
                $scope.$root.showQueryList({
                    key:'process_no',
                    header : [
                        {label: $filter('translate')('common.queryList.process_no'), code:'process_no'},
                        {label: $filter('translate')('common.queryList.process_ver'), code: 'process_ver' },
                        {label: $filter('translate')('common.queryList.process_name'), code: 'process_name' },
                        {label: $filter('translate')('common.queryList.process_issuestate_name'),code: 'process_issuestate_name'},
                        {label: $filter('translate')('common.queryList.process_description'),code: 'process_description'}
                    ],
                    query: function(conditions, feedback){
                        $scope.workItem.process_detail.forEach(function(temp){
                            temp.process_issuestate_name = get_process_issuestate(temp.process_issuestate)
                        })
                        feedback($scope.workItem.process_detail);
                    },
                    confirm: function(selectItem, dialog){
                        dialog.hide();
                        $scope.workItem.process_display = selectItem.process_no+'('+selectItem.process_ver+')';
                        $scope.workItem.process_no = selectItem.process_no;
                        $scope.workItem.process_ver = selectItem.process_ver;
                        $scope.process_op_detail = selectItem.op_station;
                        $scope.process_op_detail.forEach(function(item){
                            item.index = 0;
                        });
                    }
                });
            } else {
                $scope.$root.showAlert($filter('translate')('B0101.msg.column7'));
            }
        };

        //20220808 add by 王晴晴 for M#0103512:签核状态多国语系转化
        function get_process_issuestate(type) {
            var str = "";
            switch (type) {
                case 0:
                    str = $filter('translate')('B0101.state_list.state_0');
                    break;
                case 1:
                    str = $filter('translate')('B0101.state_list.state_1');
                    break;
                case 2:
                    str = $filter('translate')('B0101.state_list.state_2');
                    break;
                case -1:
                    str = $filter('translate')('B0101.state_list.state_3');
                    break;
            }
            return str;
        }

        $scope.confirm = function(){
            if($scope.plotItem.length != 0){
                var content = {
                    wo_no:$scope.workItem.wo_no,
                    description : $scope.workItem.description,
                    priority : $scope.workItem.priority,
                    is_urgent : $scope.workItem.is_urgent,
                    type : $scope.type,
                    plot_detail: $scope.plotItem,
                    process_no: $scope.workItem.process_no,
                    process_ver: $scope.workItem.process_ver,
                    // 使用 mdl-datepicker 日期套件更換日期後，會強制轉為 GMT 時間格式，所以需要再轉換一次。
                    default_date: $filter('date')($scope.workItem.default_date, 'yyyy/MM/dd')
                };

                var plotItem = $scope.plotItem;

                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.create_lot_process',
                    content : content,
                    success : function(data){
                        $scope.$root.showToast($filter('translate')('B0101.msg.success'), function(){
                            $scope.workItem = undefined;
                            $scope.plotItem = [];
                            $scope.wo_no = '';
                        });
                        autoPreview(plotItem); // 透過系統參數判斷是否自動預覽流程卡
                    }
                });
            } else {
                $scope.$root.showAlert($filter('translate')('B0101.msg.column3'));
            }
        };

        $scope.sendExpand = function(){
            var errorMsg = '';
            if($scope.workItem.std_qty == undefined || $scope.workItem.std_qty == ''){
                errorMsg += $filter('translate')('B0101.errorMsg.column1')+'<br>';
            } else if($scope.workItem.std_qty == 0){
                errorMsg += $filter('translate')('B0101.errorMsg.column2')+'<br>';
            }

            if($scope.workItem.expand_qty == undefined || $scope.workItem.expand_qty == ''){
                errorMsg += $filter('translate')('B0101.errorMsg.column3')+'<br>';
            } else if($scope.workItem.expand_qty == 0){
                errorMsg += $filter('translate')('B0101.errorMsg.column1')+'<br>';
            }

            if(errorMsg==''){
                var content = {
                    max_expand_qty : $scope.workItem.expand_qty,
                    wo_no : $scope.workItem.wo_no,
                    std_qty : $scope.workItem.std_qty,
                    type : $scope.type
                };

                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.wo_expand_lot_process',
                    content : content,
                    success : function(data){
                        $scope.untreated_qty_over = 0;
                        $scope.plotItem = data.wo_expand_lot_process;
                    }
                });
            } else {
                $scope.$root.showAlert(errorMsg);
            }
        };

        $scope.std_qty_isChanged = false;
        $scope.input_std_qty = function(event){
            var target = event.currentTarget;
            angular.element(target).addClass('is-focus');
            $calculater.open(function(num,dialog){
                  angular.element(target).removeClass('is-focus');
                  if(!$scope.std_qty_isChanged && $scope.workItem.std_qty != num){
                      $scope.std_qty_isChanged = true;
                  }
                  $scope.workItem.std_qty = num;
                  dialog.hide();
              
            },
            function(dialog){
                angular.element(target).removeClass('is-focus');
                dialog.hide();
            },
            {
                defaultNum : $scope.workItem.std_qty,
                decimal : true
            });
        };

        $scope.input_expand_qty = function(event){
            var target = event.currentTarget;
            angular.element(target).addClass('is-focus');
            $calculater.open(function(num,dialog){
                if(num!=0){
                    angular.element(target).removeClass('is-focus');
                    //當生產批開立的時候才要顯示
                    if($scope.type == '0' && num > (+$scope.workItem.untreated_qty)){
                        //下線數量已超過未下線數量
                        // 20211026 modify by chenshibo for#102020: 宁波杰立，生产批开立下线数量可修改大于工单数量
                        $scope.$root.showAlert($filter('translate')('B0101.msg.column4')+$scope.workItem.untreated_qty);
                    } else {
                        $scope.workItem.expand_qty = num;
                        dialog.hide();
                    }
                } else {
                    $scope.$root.showAlert($filter('translate')('B0101.msg.column5'));
                }


            },
            function(dialog){
                angular.element(target).removeClass('is-focus');
                dialog.hide();
            },
            {
                defaultNum : $scope.workItem.expand_qty,
                decimal : true
            });
        };

        $scope.untreated_qty_over = 0;
        $scope.input_plot_qty = function(event, item){
           
            var target = event.currentTarget;
            angular.element(target).addClass('is-focus');
            $calculater.open(function(num,dialog){
                if(num == 0){
                    $scope.$root.showAlert($filter('translate')('B0101.msg.column8'));
                } else {
                    angular.element(target).removeClass('is-focus');
                    if(!item.is_changed && item.plot_qty != num){
                        item.is_changed = true;
                    }
                    item.plot_qty = num;
                    $scope.untreated_qty_over = 0;
                    $scope.plotItem.forEach(function(plotDetail){
                        $scope.untreated_qty_over = $calculater.decimalAdd((+plotDetail.plot_qty), (+$scope.untreated_qty_over));
                    });
                    dialog.hide();
                }
             
            },
            function(dialog){
                angular.element(target).removeClass('is-focus');
                dialog.hide();
            },
            {
                defaultNum : item.plot_qty,
                decimal : true
            });
        };

        $scope.input_priority = function(event){
            var target = event.currentTarget;
            angular.element(target).addClass('is-focus');
            $calculater.open(function(num,dialog){
                if(num > 99){
                    $scope.$root.showAlert($filter('translate')('B0101.msg.column6'));
                } else if(num!=0){
                    angular.element(target).removeClass('is-focus');
                    $scope.workItem.priority = num;
                    dialog.hide();
                }
            },
            function(dialog){
                angular.element(target).removeClass('is-focus');
                dialog.hide();
            },
            {
                defaultNum : $scope.workItem.priority,
                decimal : false
            });
        };

        $scope.prevStation = function(item){
            if(item.index >0){
                item.index--;
            }
        };

        $scope.nextStation = function(item){
            if(item.index < item.op_station_detail.length-1){
                item.index++;
            }
        };

        // 透過系統參數判斷是否自動預覽流程卡
        function autoPreview(plotItem){
            $MMWService.pageNumberInfoGet({
                page_mode: 'sys_parameter_info_get_Condition',
                query_condition_info: [
                    {column_name: 'PARAMETERTYPE', query_mode: '0', value: 'SysInfo', merge_condition_model: 'AND' },
                    {column_name: 'PARAMETERNO', query_mode: '0', value: 'PrintRunCardModel', merge_condition_model: 'AND' }
                ]
            }, function(itemList){
                if(itemList && itemList.length > 0){
                    if(itemList[0].parameter_value === '1'){
                        var plot_detail = [];
                        plotItem.forEach(function(item){
                            plot_detail.push({
                                plot_no: item.plot_no
                            });
                        });
                        preview(plot_detail);
                    }
                }
            });
        }

        // 預覽流程卡
        var pdf_url;
        function preview(plot_detail){
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.runcard_pdf_get',
                content : {
                    course: '0',
                    plot_detail : plot_detail
                },
                success : function(data){

                    for(var i = 0; i < plot_detail.length; i++){
                        $scope.printList.push({
                            printNo: plot_detail[i].plot_no,
                            printType: '1' // 1: 流程卡打印 + 生產批開立; 3: 條碼標籤打印(補印); 4: 外包單 - 出貨打印; 5. 叫修作業;
                        });
                    }

                    pdf_url = data.runcard_pdf_get[0].url_pdf;
                    if(pdf_url.indexOf('http://') == -1){
                        pdf_url = 'http://'+config.server.ip+':'+config.server.port+ pdf_url;
                    }
                    if(config.setting.outsidePDF == 'Y'){
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try{
                            // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                            RuncardPath = remote.app.getAppPath();
                        }catch(e){
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if(!fs.existsSync(RuncardPath)){
                            fs.mkdirSync(RuncardPath);
                        }

                        // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                        // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                        fs.readdirSync(RuncardPath, (err, files) => {
                            if (err) {
                                console.log(err);
                            }
                            //listing all files using forEach
                            files.forEach((file) => {
                                // Do whatever you want to do with the file
                                fs.unlink(RuncardPath + '/' + file, (err) => {
                                    if (err) {
                                        console.debug(err);
                                    }
                                })
                            });
                        })

                        // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                        let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                        $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                            // 20230807 modify by Alan for#130433 : electron升版後，shell.openItem改成shell.openPath
                            const { shell } = window.nodeRequire('electron');
                            shell.openItem ? shell.openItem(dist_path) : shell.openPath(dist_path);
                        });
                    } else {
                        showPDFViewer(pdf_url);
                    }
                }
            });
        }

        function showPDFViewer(pdf_url){
            try{
                window.nodeRequire('nw.gui').Window.open(pdf_url, {
                    title:'PDF Viewer',
                    show: false,
                    icon:'icon/icon.png',
                    focus:true
                }, function(win) {
                    win.on('loaded', function(){
                        win.show();
                        win.print();
                    });
                });
            } catch (e){
                $scope.mode = 'print';
                document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file='+pdf_url+'&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
            }
        }

        // 列印
        $scope.print = function(){
            if(window.nodeRequire){
                var sumatraPDF = window.nodeRequire('sumatra-pdf');
                if(sumatraPDF){
                    var fs = window.nodeRequire('fs'), RuncardPath;
                    try{
                        // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                        const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                        RuncardPath = remote.app.getAppPath();
                    }catch(e){
                        RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                    }
                    RuncardPath += '\\www\\Runcard';
                    if(!fs.existsSync(RuncardPath)){
                        fs.mkdirSync(RuncardPath);
                    }
                    
                    // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                    // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                    fs.readdirSync(RuncardPath, (err, files) => {
                        if (err) {
                            console.log(err);
                        }
                        //listing all files using forEach
                        files.forEach((file) => {
                            // Do whatever you want to do with the file
                            fs.unlink(RuncardPath + '/' + file, (err) => {
                                if (err) {
                                    console.debug(err);
                                }
                            })
                        });
                    })

                    // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                    let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                    $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                        $scope.$root.showLoading();
                        window.nodeRequire('sumatra-pdf').printWithSettings({
                            path: dist_path,
                            success:function(){
                                printWiplogProcess();
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                            },
                            error:function(error){
                                // 20201104 modify by WeiTing for M#77013 - 不清楚為何列印後，實際列印一張紙和輸入成 PDF檔案都會執行 error 區域，所以目前也先列印完成後，把列印詳情回送給後台做記錄。
                                printWiplogProcess();
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                                //console.error(error);
                            }
                        });
                    });
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
            } else {
                window.frames['kmi-pdf-panel'].pdf_print();
            }
        };

        // 下載
        $scope.download = function(){
            window.frames['kmi-pdf-panel'].pdf_download();
        };

        // 取消
        $scope.cancel = function(){
            $scope.mode = 'init';
            document.getElementById('kmi-pdf-panel').src = '';
            $scope.printList = [];
        };

        // 列印完成後，需把列印詳情回送給後台做記錄
		function printWiplogProcess(){
			$MMWService.sendToServer({
				uri: 'ServicesSTD.Module_SN.print_wiplog_process',
				content : {
                    printList: $scope.printList
                },
				success : function(){
                    $scope.mode = 'init';
                    $scope.printList = [];
                }
			});
		}
        
    }
];});
